package middleware

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"home-butler/internal/consts/enums"
	"home-butler/internal/service"
	"home-butler/utility/response"
)

func init() {
	service.RegisterMiddleware(New())
}

type sMiddleware struct{}

func New() service.IMiddleware {
	return &sMiddleware{}
}

func (s sMiddleware) ResponseHandler(r *ghttp.Request) {
	r.Middleware.Next()
	// 如果已经有返回内容，那么该中间件什么也不做
	if r.Response.BufferLength() > 0 {
		return
	}
	var (
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = gerror.Code(err)
		emsg = gerror.Stack(err)
	)
	if err != nil {
		if code == gcode.CodeNil {
			code = enums.Fail
		}
		response.JsonExit(r, code, emsg)
	} else {
		response.SuccessMsg(r, res)
	}
}
